package com.nsoft.html5npub.business;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.nsoft.html5npub.utils.Constant;
import com.nsoft.html5npub.utils.engine;
import com.nsoft.html5npub.utils.utils;

public class SyncBookThread extends Thread {
	
	private BookSyncListener syncHandler;
	
	public void setBookSyncListener(
				BookSyncListener _syncHandler){
		this.syncHandler=_syncHandler;
	}
	
	public static final int SYNC_SOURCE_HISTORY=1;
	public static final int SYNC_SOURCE_SERVER=0;
	
	public static final int SYNC_SERVER_FAILED=1;
	public static final int SYNC_LOCAL_FAILED=2;
	public static final int SYNC_COMPLETED=0;
	
	Context context;
	ProgressDialog pd;
	
	int syncSource=SYNC_SOURCE_HISTORY;
	int syncRes=SYNC_COMPLETED;
	
	public SyncBookThread(Context _ctx,
				ProgressDialog _pd,int syncSrc){
		this.context=_ctx;
		this.pd=_pd;
		this.syncSource=syncSrc;
	}
	
	public void run(){
		/**
		 * 1. get book list from database first
		 */
		dbengine.getDownloadedBookList();
		
		if (syncSource==SYNC_SOURCE_SERVER){
			try{
				/**
				 * 2.1 match book list from server with
				 * list from database
				 */
				engine.getBookListFromServer();
				engine.getIconsFromServer();
			}catch(Exception e){
				Log.v("SyncBookThread<-Server",
       				e.getClass()+": "+e.getMessage());
				syncRes=SYNC_SERVER_FAILED;
			}
		}else if (syncSource==SYNC_SOURCE_HISTORY){
			try{
				/**
				 * 2.2 match book list from local with 
				 * list from database
				 */
				engine.getBookListFromHistory();
			}catch(Exception e){
				Log.v("SyncBookThread<-HistoryList",
       				e.getClass()+": "+e.getMessage());
				syncRes=SYNC_LOCAL_FAILED;
			}
		}
		handler.sendEmptyMessage(0);
	}
	
	@SuppressLint({ "HandlerLeak" })
	private Handler handler=new Handler(){
		@Override
		public void handleMessage(android.os.Message msg) {
			pd.dismiss();
			
			if (syncRes==SYNC_SERVER_FAILED){
				utils.showInfo(context,
					Constant.DIALOG_ALERT,
					Constant.booklist.
						BLF_LOAD_FROMSERVER_FAILED);
			}else if (syncRes==SYNC_LOCAL_FAILED){
				utils.showInfo(context,
					Constant.DIALOG_ALERT,
					Constant.booklist.
						BLF_LOAD_FROMLOCAL_FAILED);
			}
			
			if (syncHandler!=null)
				syncHandler.synchronizeDone();
		}
	};
}
